package org.bao.bestmatch;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.bao.bestmatch.model.Module;

/**
 * DataReader reads data from one given MS-EXCEL file,and gen. Module objects.
 * @author baoxiwu<bb@feijiao.info>,Cell&Module,BOE DT
 * @version 0.9.0
 * @since 2010-11-19
 * @license LGPL
 * 
 */
public class DataReader {
	public static final String 	XSL_FORMAT_SHEET_NAME_TFT = "TFT";
	public static final String 	XSL_FORMAT_SHEET_NAME_CF = "CF";
	
	public static final String 	XSL_FORMAT_CST_ID = "CST_ID";
	public static final String 	XSL_FORMAT_GLASS_ID = "GLASS_ID";
	public static final String 	XSL_FORMAT_GLASS_GRADE = "GLASS_GRADE";
	public static final String 	XSL_FORMAT_TYPE = "TYPE";
	
	
	private LinkedList<Module> tfts = new LinkedList<Module>();
	private LinkedList<Module> cfs = new LinkedList<Module>();
	
	private Module module = null;
	private File file = null;
	private int type = Module.MODULE_TYPE_TFT;
	
	
	public DataReader(String path){
		this.file = new File(path);
	}
	
	
	public Object[] crawl(){
		Object[] modules = new Object[2];
		
		Workbook wb = null;
		
		try {
			wb = Workbook.getWorkbook(file);
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(null == wb){
			return null;
		}
		
		Sheet[] sheets = wb.getSheets();
		
		//assume ONLY fisrt TWO sheets to handle.
		if(sheets != null && sheets.length > 0){
			for(int i = 0; i < (sheets.length > 2 ? 2 : sheets.length); i++){
				if(sheets[i].getName().equals(DataReader.XSL_FORMAT_SHEET_NAME_CF)){
					this.type = Module.MODULE_TYPE_CF;
					
					for(int j = 0; j < sheets[i].getRows(); j++){
						Cell[] cells = sheets[i].getRow(j);
						
						//assume only 4 columns in one sheet.
						if(cells != null && cells.length == 4){
							if(!cells[0].getContents().equals(DataReader.XSL_FORMAT_CST_ID)){
								module = new Module(this.type,cells[0].getContents(),cells[1].getContents(),cells[2].getContents());
								cfs.add(module);
							}
						}
					}
				}
				else{
					this.type = Module.MODULE_TYPE_TFT;
					
					for(int j = 0; j < sheets[i].getRows(); j++){
						Cell[] cells = sheets[i].getRow(j);
						
						//assume only 4 columns in one sheet.
						if(cells != null && cells.length == 4){
							if(!cells[0].getContents().equals(DataReader.XSL_FORMAT_CST_ID)){
								module = new Module(this.type,cells[0].getContents(),cells[1].getContents(),cells[2].getContents());
								tfts.add(module);
							}
						}
					}
				}
			}
		}
		
		modules[0] = tfts;
		modules[1] = cfs;
		
		return modules;
	}
}
